package com.lantosec.hmrp.modules.warning.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lantosec.hmrp.core.shiro.TokenUtil;
import com.lantosec.hmrp.core.util.StringUtils;
import com.lantosec.hmrp.modules.eval.entity.EvalItem;
import com.lantosec.hmrp.modules.eval.service.IEvalItemService;
import com.lantosec.hmrp.modules.warning.entity.*;
import com.lantosec.hmrp.modules.warning.mapper.WarningRuleMapper;
import com.lantosec.hmrp.modules.warning.service.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 * 预警规则 服务实现类
 * </p>
 *
 * @author AutoCode
 * @since 2020-05-19
 */
@Service
@Primary
@Log4j2
@SuppressWarnings("all")
public class WarningRuleServiceImpl extends ServiceImpl<WarningRuleMapper, WarningRule> implements IWarningRuleService {

    @Autowired
    private IWarningNotifierDeptService deptService;

    @Autowired
    private IWarningMessageService messageService;

    @Autowired
    private IWarningNotifierService notifierService;

    @Autowired
    private IWarningReportedService reportedService;

    @Autowired
    private IEvalItemService itemService;


    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public String create(Map<String, Object> map, HttpServletRequest request) {
        //获取token中的用户信息
        String token = request.getHeader("token");
        //获取预警通知设置对象
        Map result = (Map) map.get("notice");
        //保存预警规则主表信息
        WarningRule warningRule = getWarningRule(map, token, result);
        String ruleId = warningRule.getRuleId();
        //保存预警信息明细表信息
        saveWarningInfo(map, result, ruleId);
        return ruleId;
    }

    private WarningRule getWarningRule(Map<String, Object> map, String token, Map result) {
        String rule = JSON.toJSONString(map.get("rule"));
        JSONObject jsonObject = JSONObject.parseObject(rule);
        WarningRule warningRule = JSONObject.toJavaObject(jsonObject, WarningRule.class);
        warningRule = saveBaseInfo(token, result, warningRule);
        //保存信息至warning_rule表
        baseMapper.insert(warningRule);
        return warningRule;
    }

    private WarningRule saveBaseInfo(String token, Map result, WarningRule warningRule) {
        String userId = TokenUtil.getUserId();
        warningRule.setCreateUserId(userId);
        warningRule.setCreateTime(new Date());
        warningRule.setEditTime(new Date());
        warningRule.setEditUserId(userId);
        warningRule.setFlag(0);
        warningRule.setRepeal(0);
        boolean containsKey = result.containsKey("thresholdValue");
        if (containsKey) {
            Object value = result.get("thresholdValue");
            if (null != value) {
                warningRule.setThresholdValue(value.toString());
            }
        }
        boolean userFlag = result.containsKey("userField");
        if (userFlag) {
            Object field = result.get("userField");
            if (null != field) {
                warningRule.setUserField(field.toString());
            }
        }
        boolean deptFlag = result.containsKey("deptField");
        if (deptFlag) {
            Object field = result.get("deptField");
            if (null != field) {
                warningRule.setDeptField(field.toString());
            }
        }
        return warningRule;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public String saveWarningInfo(Map<String, Object> map, Map result, String ruleId) {
        //预警通知人
        String notifiersList = JSON.toJSONString(result.get("notifier"));
        List<WarningNotifier> notifiers = JSON.parseArray(notifiersList, WarningNotifier.class);
        if (notifiers != null && notifiers.size() > 0) {
            notifiers.forEach(it -> {
                it.setRuleId(ruleId);
                notifierService.save(it);
            });
        }
        //预警信息
        String messagesJson = JSON.toJSONString(result.get("message"));
        List<WarningMessage> messages = JSON.parseArray(messagesJson, WarningMessage.class);
        if (messages != null && messages.size() > 0) {
            messages.forEach(it -> {
                baseMapper.saveWarningMessage(it, ruleId);
            });
        }
        //预警部门通知人
        String notifierDeptsJson = JSON.toJSONString(result.get("notifierDept"));
        List<WarningNotifierDept> notifierDepts = JSON.parseArray(notifierDeptsJson, WarningNotifierDept.class);
        if (notifierDepts != null && notifierDepts.size() > 0) {
            notifierDepts.forEach(it -> {
                it.setRuleId(ruleId);
                String notifierPositionId = it.getNotifierPositionId();
                notifierPositionId = StringUtils.splitStrByChar(notifierPositionId, "-");
                it.setNotifierPositionId(notifierPositionId);
                deptService.save(it);
            });
        }
        //预警上报人
        String reportedJson = JSON.toJSONString(result.get("report"));
        List<WarningReported> reporteds = JSON.parseArray(reportedJson, WarningReported.class);
        if (reporteds != null && reporteds.size() > 0) {
            reporteds.forEach(it -> {
                it.setRuleId(ruleId);
                reportedService.save(it);
            });

        }
        //预警处置方式
        String ruleJson = JSON.toJSONString(map.get("rule"));
        JSONObject jsonObject = JSONObject.parseObject(ruleJson);
        WarningRule warningRule = JSONObject.toJavaObject(jsonObject, WarningRule.class);
        if (2 == warningRule.getDisposalMode()) {
            String ruleEval = (String) map.get("ruleEval");
            List<String> list = Arrays.asList(ruleEval.split(","));
            if (null != list && list.size() > 0) {
                list.forEach(it -> {
                    baseMapper.saveWarningRuleEval(it, ruleId);
                });
            }
        }
        return ruleId;
    }

    @Override
    public Map<String, Object> queryDetails(String id) {
        Map<String, Object> map = new HashMap<>();
        List<EvalItem> list = new ArrayList<>();
        WarningRule warningRule = baseMapper.selectOne(new QueryWrapper<WarningRule>()
                .eq(String.valueOf(WarningRule.ColName.rule_id), id));
        map.put("warningRule", warningRule);
        //预警信息
        List<WarningMessage> messages = messageService.list(new QueryWrapper<WarningMessage>()
                .eq(String.valueOf(WarningMessage.ColName.rule_id), id));
        //预警部门通知人
        List<WarningNotifierDept> depts = deptService.list(new QueryWrapper<WarningNotifierDept>()
                .eq(String.valueOf(WarningNotifierDept.ColName.rule_id), id));
        //预警通知人
        List<WarningNotifier> notifiers = notifierService.list(new QueryWrapper<WarningNotifier>()
                .eq(String.valueOf(WarningNotifier.ColName.rule_id), id));
        //预警上报人
        List<WarningReported> reporteds = reportedService.list(new QueryWrapper<WarningReported>()
                .eq(String.valueOf(WarningReported.ColName.rule_id), id));
        WarningDetails details = new WarningDetails(notifiers, messages, depts, reporteds);
        map.put("details", details);
        List<WarningRuleEval> ruleEvals = baseMapper.selectWarningRuleEval(id);
        if (null != ruleEvals && ruleEvals.size() > 0) {
            ruleEvals.forEach(it -> {
                String evalItemId = it.getEvalItemId();
                EvalItem item = itemService.getOne(new QueryWrapper<EvalItem>()
                        .eq(String.valueOf(EvalItem.ColName.eval_item_id), evalItemId));
                list.add(item);
            });
        }
        map.put("evalItem", list);
        return map;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public String updateInfo(Map<String, Object> map, HttpServletRequest request) {
        String ruleId = (String) map.get("ruleId");
        //删除预警通知人
        baseMapper.deleteWarningNotifier(ruleId);
        //删除预警部门通知人
        baseMapper.deleteWarningNotifierDept(ruleId);
        //删除预警处置标准
        baseMapper.deleteWarningRuleEval(ruleId);
        //删除预警信息
        baseMapper.deleteWarningMessage(ruleId);
        //删除预警上报人
        baseMapper.deleteWarningReported(ruleId);
        //获取token中的用户信息
        String token = request.getHeader("token");
        //获取预警通知设置对象
        Map result = (Map) map.get("notice");
        saveWarningInfo(map, result, ruleId);
        //更新预警规则表
        String rule1 = JSON.toJSONString(map.get("rule"));
        JSONObject jsonObject = JSONObject.parseObject(rule1);
        WarningRule warningRule = JSONObject.toJavaObject(jsonObject, WarningRule.class);
        warningRule = saveBaseInfo(token, result, warningRule);
        baseMapper.updateById(warningRule);
        return ruleId;
    }

    @Override
    public void changeState(String id, Integer state) {
        baseMapper.changeState(id, state);
    }
}
